//
//  CommonImageService.m
//  TKnowBox
//
//  Created by milo on 15/6/14.
//  Copyright (c) 2015年 knowin. All rights reserved.
//

#import "SimImagePickerKit.h"
#import "SimMulImagePickerVC.h"
#import "SimAlbumsListVC.h"
#import "SimImageEditorVC.h"
#import "SimDragNavController.h"
#import "SimPhotoBrowser.h"
#import "SimActionSheet.h"
#import "SimAlertView.h"
#import "UIWindow+SimAddition.h"
#import "SimLoading.h"
#import <objc/runtime.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>

SimImpValue(kSimImagePickerShadowImage, UIImage *);
SimImpValue(kSimImagePickerNavBarColor, UIColor *);
SimImpValue(kSimImagePickerNavarStyle, NSNumber *);

static void * const PresentKitAssociatedStorageKey = (void*)&PresentKitAssociatedStorageKey;

@interface SimImagePickerKit()<SimMulImagePickerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>
{
    UIPopoverController* _popover;
}

@end

@implementation SimImagePickerKit

+ (instancetype)instance
{
    return[[self alloc] init];
}

- (id)init
{
    self = [super init];
    if (self) {
        _maxPicCount = 1;
    }
    
    return self;
}

- (void)dealloc
{
    NSLog(@"dealloc");
}


+ (void)showActionSheet:(NSString *)title select:(void(^)(NSInteger selectedIndex))selectedBlock
{
    SimActionSheet *sheet = [[SimActionSheet alloc] initWithTitle:title];
    sheet.totalBtnCount = ^{
        return 2;
    };
    sheet.btnTextColorForIndex = ^(NSInteger index){
        return HEXRGBCOLOR(0x525252);
    };
    sheet.btnTitleForIndex = ^(NSInteger index){
        switch (index) {
            case IPSIT_Camera:
                return @"拍照";
            case IPSIT_Photo:
                return @"从手机相册选择";
        }
        return @"取消";
    };
    sheet.clickOnIndex = ^(NSInteger index){
        if (index == IPSIT_Cancel) {
            return;
        }
        
        if (selectedBlock) {
            selectedBlock(index);
        }
    };
    
    [sheet showInView:[UIWindow getTopWindow]];
}

- (void)showImagePickerInVC:(UIViewController *)vc
{
    if ([[self class] checkMediaAuthStatus: (self.pickerType != IPT_Camera)] == NO) {
        return;
    }
    
    if (self.pickerType == IPT_MulPhoto) {
        SimMulImagePickerVC *picker = [[SimMulImagePickerVC alloc] init];
        picker.maximumNumberOfSelection = _maxPicCount;
        picker.allowsMultipleSelection = YES;
        picker.delegate = self;
        picker.filterType = SimImagePickerFilterTypePhotos;
        [vc presentViewController:picker animated:YES completion:nil];
        objc_setAssociatedObject(picker, PresentKitAssociatedStorageKey, self, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    else{
        BOOL isCamera = (self.pickerType == IPT_Camera);
        UIImagePickerControllerSourceType sourType =  isCamera ? UIImagePickerControllerSourceTypeCamera : UIImagePickerControllerSourceTypePhotoLibrary;
        
        BOOL available = [UIImagePickerController isSourceTypeAvailable:sourType];
        if (!available) {
            SimAlertView *alert = [[SimAlertView alloc]
                                      initWithTitle:@"提示"
                                      message:isCamera ? @"该设备没有摄像头" : @"未能连接到图片库"
                                      btns:@[@"确认" ] dismissBlock:nil];
            [alert show];
        }
        else{
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            [picker.navigationBar setTranslucent:NO];
            picker.navigationBar.shadowImage = SimValue(kSimImagePickerShadowImage, [UIImage new]);
            UIColor *tintColor = SimValue(kSimImagePickerNavBarColor, ABOVE_IOS7 ? [UIColor whiteColor] : HEXRGBCOLOR(0x46b789));
            picker.delegate = self;
            picker.navigationBar.tintColor = tintColor;
            picker.sourceType = sourType;
            picker.allowsEditing = self.allowsEditing;
            objc_setAssociatedObject(picker, PresentKitAssociatedStorageKey, self, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
            
            if (DEVICE_IS_IPAD && sourType == UIImagePickerControllerSourceTypePhotoLibrary) {
                if (_popover) {
                    [_popover dismissPopoverAnimated:NO];
                    _popover = nil;
                }
                _popover = [[UIPopoverController alloc] initWithContentViewController:picker];
                _popover.delegate=self;
                [_popover presentPopoverFromRect:CGRectMake(0, 0, vc.view.frame.size.width, 100)
                                          inView:vc.view
                        permittedArrowDirections:UIPopoverArrowDirectionUp
                                        animated:YES];

            }
            else{
                if([[[UIDevice currentDevice] systemVersion] floatValue] >=8.0) {
                    vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
                }
                [vc presentViewController:picker animated:YES completion:nil];
            }

        }
    }    
}

- (SimPhotoBrowser *)showImageBrowserInVC:(UIViewController *)vc
{
    if (self.imageContents.count == 0) {
        return nil;
    }
    SimPhotoBrowser *photoBrowserVC = [[SimPhotoBrowser alloc] initWithImageContents:self.imageContents
                                                                               index:self.initIndex];
    self.photoBrowserVC = photoBrowserVC;
    photoBrowserVC.didFinishBrowser = ^(SimPhotoBrowser *browser, BOOL changed){
        if (_finishImageBrowser) {
            _finishImageBrowser(browser, changed);
        }
    };
    [self innerShowBrowser:photoBrowserVC inVC:vc];
    return photoBrowserVC;
}

- (void)showImagewEditInVC:(UIViewController *)vc
{
    for (id obj in self.imageContents) {
        BOOL isEditModel = [obj isKindOfClass:[SimImageEditModel class]];
        NSAssert(isEditModel, @"edit mode should only set SimImageEditModel");
        if(!isEditModel){
            return;
        }
    }
    SimPhotoBrowser *photoBrowserVC = [[SimPhotoBrowser alloc] initWithImageContents:self.imageContents
                                                                               index:self.initIndex];
    photoBrowserVC.enableEdit = YES;
    photoBrowserVC.enableDelete = YES;
    photoBrowserVC.didFinishBrowser = ^(SimPhotoBrowser *browser, BOOL changed){
        if (_finishImageBrowser) {
            _finishImageBrowser(browser, changed);
        }
    };
    
    [self innerShowBrowser:photoBrowserVC inVC:vc];
}

- (void)innerShowBrowser:(SimPhotoBrowser *)photoBrowserVC inVC:(UIViewController *)vc
{
    if (vc.navigationController != nil) {
        [(UINavigationController *)[vc navigationController] pushViewController:photoBrowserVC animated:YES];
    }
    else{
        [vc presentViewController:photoBrowserVC animated:YES completion:nil];
    }    
}

#pragma mark -  QBImagePickerController Delegate
- (void)simImagePicker:(SimMulImagePickerVC *)imagePicker didFinishPickerWithAssets:(NSArray *)assets
{
    NSInteger totalCount = imagePicker.selectedAssets.count;
    
    __block NSInteger index = 0;
    __block NSMutableArray *selectedImages = [NSMutableArray array];
    for (ALAsset *asset in imagePicker.selectedAssets) {
        ALAssetRepresentation *asserRep = [asset defaultRepresentation];
        CGImageRef imageRef = [asserRep fullScreenImage];
        UIImage *image = [UIImage imageWithCGImage:imageRef];
        index = index+1;
        if (image) {
            [selectedImages addObject:image];
        }
        if (index == totalCount) {
            if (_finishPickerWithImages) {
                _finishPickerWithImages(selectedImages);
            }
            objc_setAssociatedObject(imagePicker, PresentKitAssociatedStorageKey, nil, OBJC_ASSOCIATION_RETAIN);
        }

    }
    [imagePicker dismissViewControllerAnimated:YES completion:nil];
}

- (void)simImagePickerDidCancel:(SimMulImagePickerVC *)imagePicker
{
    if (_finishPickerWithImages) {
        _finishPickerWithImages(nil);
    }
    [imagePicker dismissViewControllerAnimated:YES completion:nil];
    objc_setAssociatedObject(imagePicker, PresentKitAssociatedStorageKey, nil, OBJC_ASSOCIATION_RETAIN);
}

- (BOOL)simImagePicker:(SimMulImagePickerVC *)imagePicker shouldSelectAsset:(ALAsset *)asset
{
    NSInteger canSelectCount = _maxPicCount - _currentCount;
    if (imagePicker.selectedAssets.count >= canSelectCount ) {
        NSString *tipStr = [NSString stringWithFormat:@"最多只能添加%ld张图片", (long)_maxPicCount];
        [SimLoading showLoadingType:LT_Warning content:tipStr];
        return NO;
    }
    
    return YES;
}


#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *image = nil;
    if (self.allowsEditing) {
        image = info[UIImagePickerControllerEditedImage];
    }
    else{
        image = info[UIImagePickerControllerOriginalImage];
    }
    if (_finishPickerWithImages) {
        _finishPickerWithImages(@[image]);
    }
    
    if (_popover) {
        [_popover dismissPopoverAnimated:NO];
        _popover = nil;
    }
    else{
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
    objc_setAssociatedObject(picker, PresentKitAssociatedStorageKey, nil, OBJC_ASSOCIATION_RETAIN);
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    if (_finishPickerWithImages) {
        _finishPickerWithImages(nil);
    }
    
    if (_popover) {
        [_popover dismissPopoverAnimated:NO];
        _popover = nil;
    }
    else{
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
    objc_setAssociatedObject(picker, PresentKitAssociatedStorageKey, nil, OBJC_ASSOCIATION_RETAIN);
}

- (void)navigationController:(UINavigationController *)navigationController
      willShowViewController:(UIViewController *)viewController
                    animated:(BOOL)animated {
    
    if ([navigationController isKindOfClass:[UIImagePickerController class]] &&
        ((UIImagePickerController *)navigationController).sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
        UIStatusBarStyle style = [SimValue(kSimImagePickerNavarStyle, @(UIStatusBarStyleLightContent)) integerValue];
        [[UIApplication sharedApplication] setStatusBarStyle:style animated:NO];
    }
}

+ (BOOL)checkMediaAuthStatus:(BOOL)isPhoto
{
    ALAuthorizationStatus authStatus = ALAuthorizationStatusAuthorized;
    if (isPhoto) {
        authStatus = [ALAssetsLibrary authorizationStatus];
    }
    else if(ABOVE_IOS7){
        authStatus = (ALAuthorizationStatus)[AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    }
    
    if (authStatus == ALAuthorizationStatusRestricted || authStatus == ALAuthorizationStatusDenied) {
        NSString *title = [NSString stringWithFormat:@"无权限使用%@", isPhoto ? @"相册" : @"拍照"];
        NSString *message = [NSString stringWithFormat:@"请前往手机【设置】-【隐私】-【%@】中开启此应用权限", isPhoto ? @"照片" : @"相机"];
        BOOL belowIOS10 = (IOS_VERSION_FLOAT < 10.0f);
        SimAlertView *alert = [[SimAlertView alloc] initWithTitle:title
                                                          message:message
                                                             btns:belowIOS10 ? @[@"取消", @"去设置"] :  @[@"知道了"]
                                                     dismissBlock:^(NSInteger selectedIndex) {
                                                         if (belowIOS10 && selectedIndex == 1) {
                                                             [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=privacy"]];
                                                         }
                                                     }];
        
        [alert show];
        
        return NO;
    }
    
    return YES;
}

@end
